import userStore from '@/store/user';
import CryptoJS from 'crypto-js';
import { Base64, toUtf8 } from '@/utils/tools.js';

let baseUrl = import.meta.env.VITE_APP_BASE_API;

let loadingCount = 0;

function closeLoading(custom) {
  if (custom.loading && loadingCount > 0) {
    loadingCount--;
  }
  if (loadingCount === 0) {
    uni.hideLoading();
  }
}

let baseHeader = {
  Authorization: '',
  'YM-Client-Type': 2,
  'Content-Type': 'application/json;charset=utf-8'
};

export function request(options = {}, custom = { loading: true, toast: true }) {
  const user = userStore();

  return new Promise((resolve, reject) => {
    if (custom.loading) {
      loadingCount++;
      if (loadingCount === 1) {
        uni.showLoading({
          title: '加载中',
          mask: true
        });
      }
    }

    if (user.token) {
      baseHeader.Authorization = user.token;
    }

    if (options.header) {
      baseHeader = { ...baseHeader, ...options.header };
    }

    const API_PARAMS_SIGN =
      'RSgeuzmNnpSsyh11EVRaC2Ygm8XpS2R6WfGH36xDrxIhLZBqCvKrXyFBbxw4jJpEe90DxyzhJHBM67yIUu4HsLMGGU9WlgWztY8LaG5P4T3hVwBp1cA3SpTL9qcYQ3JG5YNsL6sRvGoYWrSxJG2u5bEiKEbeTcpa0TeJ5kDK1kapgG9EgwYF7mz8D4DQxb3V2KMjdG4kYarIqONpTZnwPkXLwuOvGyUGRWxxNJpLM2JxoBYLg1BM5uACB7Fa19mIJKDfu8NkRcFFidJ8rRRtjvso3p6NkfPVf121JuTeEdwb';
    let paramsData = options.data;
    // 正式环境加密
    if (import.meta.env.VITE_APP_BASE_API === import.meta.env.VITE_APP_ENCRYPT_URL) {
      let base64 = options.data || {};
      let hashInHex = '';
      base64 = Base64(toUtf8(JSON.stringify(base64)));
      const hash = CryptoJS.HmacSHA256(base64, API_PARAMS_SIGN);
      hashInHex = CryptoJS.enc.Hex.stringify(hash);
      paramsData = {
        data: base64,
        sign: hashInHex
      };
    }

    const params = {
      url: baseUrl + options.url,
      // data: options.data,
      data: paramsData,
      method: options.method || 'POST',
      timeout: options.timeout || 60000,
      header: baseHeader
    };

    uni.request({
      ...params,
      success: (result) => {
        const code = result.data.code || 200;
        const msg = result.data.msg;
        closeLoading(custom);
        if (code === 200) {
          if (result.data?.token) {
            // 说明是登录接口
            user.setToken(result.data.token);
          } else if (result.data?.data?.token) {
            // 说明是微信登录接口
            user.setToken(result.data.data.token);
          }
          resolve(result.data);
        } else if (msg === '该手机号已注册') {
          resolve(result.data);
        } else if (code === 401) {
          uni.showToast({
            title: '您未登录，请登录',
            icon: 'none'
          });
          uni.reLaunch({
            url: '/pages/login/phoneQuick'
          });
        } else {
          if (custom.toast) {
            uni.showToast({
              title: msg,
              icon: 'none'
            });
          }
          reject();
        }
      },
      fail: () => {
        closeLoading(custom);
        reject();
      }
    });
  });
}
